import LoadingView from './views/LoadingView.vue';
import ErrorLoadView from './views/ErrorLoadView.vue';
import { defineAsyncComponent, reactive } from 'vue';
import { ContryHelper } from './lib/ContryHelper';
import { SystemUsersHelper } from './lib/SystemUsersHelper';


export class Global {
    static UserInfo = reactive({
        Token: "",
        Name: "",
        Role: "",
    });

    static Title = reactive({
        Login: "Admin",
        System: "AdminCore",
        SystemShort: "AdminCore"
    });
    static ServerUrl: string = <any>process.env.ServerUrl;
    static UploadFileUrl: string;
    static modules: any;

    static init = () => {

        var userStr = localStorage.getItem("userinfo");
        if (userStr) {
            try {
                Global.UserInfo = JSON.parse(userStr);
            } catch (error) {

            }
        }
        if (Global.ServerUrl == "..") {
            Global.ServerUrl = `${location.protocol}//${location.host}`;
        }
        Global.UploadFileUrl = `${Global.ServerUrl}/UploadFile/Upload`;

        ContryHelper.init();
        SystemUsersHelper.init();
    }

    static listToChildrenDatas = (datas: any[], parentId: any): any[] => {
        var ret = datas.filter(x => x.ParentId == parentId);
        ret.forEach(item => {
            item.children = Global.listToChildrenDatas(datas, item.id);
        });
        return ret;
    }

    static objectToArray = (obj: any): any[] => {
        var arr = <any[]>[];
        for (var p in obj) {
            arr.push({ key: p, value: obj[p] });
        }
        return arr;
    }

    static arrayToObject = (arr: any[]): any => {
        var obj = <any>{};
        arr.forEach(item => {
            if (item.key) {
                obj[item.key] = item.value;
            }
        })
        return obj;
    }

    static changeSortInParent = (item: any, parentItems: any[]) => {

        var index = parentItems.indexOf(item);
        if (index >= 0) {
            parentItems.splice(index, 1);
        }
        Global.insertToParent(item, parentItems);
    }

    static insertToParent = (item: any, parentItems: any[]) => {

        for (var i = parentItems.length - 1; i >= 0; i--) {
            var other = parentItems[i];
            if (item.Sort >= other.Sort) {
                parentItems.splice(i + 1, 0, item);
                return;
            }
        }
        parentItems.splice(0, 0, item);
    }

    /**将变量转为json字符串显示 */
    static formatObject = (row: any, column: any, cellValue: any) => {
        if (!cellValue)
            return "";

        if(typeof cellValue == "object")
            return JSON.stringify(cellValue);
        return cellValue;
    };

    /**不考虑时区，显示日期部分 */
    static formatToLocalDate = (row: any, column: any, cellValue: any) => {
        if (!cellValue)
            return "";

        // 将字符串解析为Date对象
        var utcTime = new Date(cellValue.replace("T"," ").replace("Z",""));

        return utcTime.toLocaleDateString();

    };

    static formatUTCToLocal = (row: any, column: any, cellValue: any) => {
        if (!cellValue)
            return "";

        if (typeof cellValue == "object" && cellValue.getDate) {
            return cellValue.toLocaleString();
        }

        // 将字符串解析为Date对象
        var timeObj = new Date(cellValue);
        return timeObj.toLocaleString();

    };

    /** */
    static getContryName = (row: any, column: any, cellValue: any) => {
        if (!cellValue)
            return "";

        return ContryHelper.getContryName(cellValue);
    };

    static getUserName = (row: any, column: any, cellValue: any) => {
        if (!cellValue)
            return "";

        return SystemUsersHelper.getUserName(cellValue);
    };

    static showInfo = (text: string) => {
        ElMessage.warning(text);
    }

    static showError = (err: any) => {
        if (!err) {
            err = "unkonw error";
        }
        if (err && typeof err === "string") {
            ElMessage.error(err);
            return;
        }


        console.error("showError", err);
        if (err && err.statusCode == 401) {
            Global.UserInfo.Token = "";
            localStorage.removeItem("userinfo");
            location.href = "/#/login";
            return;
        }
        else if (err && err.statusCode == 403) {
            ElMessage.error("无权限操作");
            return;
        }
        if (err.msg) {
            ElMessage.error(err.msg);
        }
        else if (err.message) {
            ElMessage.error(err.message);
        }
        else {
            ElMessage.error(JSON.stringify(err));
        }
    }

    static cachedViews = <any>{};
    static removeViewCache = (path: string) => {
        var item = Global.cachedViews[path];
        Global.cachedViews[path] = null;
        return item;
    }

    static removeAllViewCache = () => {
        for (var p in Global.cachedViews) {
            delete Global.cachedViews[p];
        }
    }

    static asyncLoadView = (path: string) => {
        if (Global.cachedViews[path])
            return Global.cachedViews[path];

        Global.cachedViews[path] = defineAsyncComponent({
            loader: <any>Global.modules[`./views/${path}.vue`],
            loadingComponent: LoadingView, // 加载中显示的组件
            errorComponent: ErrorLoadView, // 加载出错显示的组件
            delay: 500, // 在显示loadingComponent组件之前, 等待多长时间
            timeout: 10000, // 加载超时的时间（毫秒）
            /**
              * err: 错误信息,
              * retry: 函数, 调用retry尝试重新加载
              * attempts: 记录尝试的次数
              */
            onError: (err, retry, fail, attempts) => {
                if (attempts < 2) {
                    window.setTimeout(retry, 1000);
                }
                else {
                    fail();
                }
            }
        });
        return Global.cachedViews[path];
    }
}